<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>视频解析</span>
        </div>
      </template>
      <div class="input-container">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item label="视频链接" prop="url">
            <el-input 
              v-model="form.url" 
              placeholder="请输入需要解析的视频链接" 
              clearable
              @keyup.enter="handleParse"
            >
              <template #append>
                <el-button @click="handleParse" :loading="loading" type="primary">
                  <el-icon><VideoPlay /></el-icon> 解析
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <div v-if="parseResult" class="result-container">
        <el-divider content-position="center">解析结果</el-divider>
        
        <div class="video-info">
          <div class="video-title">
            <h3>{{ parseResult.title }}</h3>
          </div>
          
          <div class="video-meta">
            <span v-if="parseResult.author">作者: {{ parseResult.author }}</span>
            <span v-if="parseResult.duration">时长: {{ parseResult.duration }}</span>
            <span v-if="parseResult.platform">平台: {{ parseResult.platform }}</span>
          </div>
          
          <div class="video-cover" v-if="parseResult.cover">
            <el-image 
              :src="parseResult.cover" 
              fit="cover"
              :preview-src-list="[parseResult.cover]"
            ></el-image>
          </div>
          
          <div class="video-player" v-if="parseResult.playUrl">
            <video 
              controls 
              :src="parseResult.playUrl" 
              style="width: 100%; max-height: 500px;"
            ></video>
          </div>
          
          <div class="download-options" v-if="parseResult.downloadUrls && parseResult.downloadUrls.length > 0">
            <h4>下载选项</h4>
            <el-table :data="parseResult.downloadUrls" style="width: 100%">
              <el-table-column prop="quality" label="清晰度" width="180"></el-table-column>
              <el-table-column prop="size" label="大小" width="180"></el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleDownload(scope.row.url)"
                  >
                    下载
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small" 
                    @click="copyUrl(scope.row.url)"
                  >
                    复制链接
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <div class="history-container" v-if="parseHistory.length > 0">
        <el-divider content-position="center">解析历史</el-divider>
        <el-table :data="parseHistory" style="width: 100%">
          <el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
          <el-table-column prop="platform" label="平台" width="120"></el-table-column>
          <el-table-column prop="parseTime" label="解析时间" width="180"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="loadHistoryItem(scope.row)"
              >
                重新加载
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="removeHistoryItem(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="tips-container">
        <el-divider content-position="center">使用说明</el-divider>
        <el-alert
          title="支持的平台"
          type="info"
          :closable="false"
          description="目前支持抖音、快手、哔哩哔哩、西瓜视频、微博视频等平台的视频解析。"
        >
        </el-alert>
        <el-alert
          title="使用方法"
          type="success"
          :closable="false"
          description="复制视频分享链接，粘贴到上方输入框，点击解析按钮即可。"
          style="margin-top: 10px;"
        >
        </el-alert>
        <el-alert
          title="注意事项"
          type="warning"
          :closable="false"
          description="部分视频可能因版权或其他原因无法解析，请见谅。解析出的视频仅供个人学习使用，请勿用于商业用途。"
          style="margin-top: 10px;"
        >
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { parseVideo, getParseHistory, deleteParseHistory } from '@/api/video/parse'

// 表单引用
const formRef = ref(null)

// 加载状态
const loading = ref(false)

// 表单数据
const form = reactive({
  url: ''
})

// 表单验证规则
const rules = {
  url: [
    { required: true, message: '请输入视频链接', trigger: 'blur' },
    { 
      pattern: /^(https?:\/\/|www\.).+/i, 
      message: '请输入有效的链接地址', 
      trigger: 'blur' 
    }
  ]
}

// 解析结果
const parseResult = ref(null)

// 解析历史
const parseHistory = ref([])

// 处理视频解析
const handleParse = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      parseVideo(form.url).then(response => {
        parseResult.value = response.data
        // 添加到历史记录
        addToHistory(parseResult.value)
        // 获取最新历史记录
        getHistory()
      }).catch(error => {
        ElMessage.error(error.message || '解析失败，请检查链接是否正确')
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

// 处理下载
const handleDownload = (url) => {
  // 创建一个隐藏的a标签用于下载
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = parseResult.value.title || '视频下载'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 复制链接
const copyUrl = (url) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 添加到历史记录
const addToHistory = (result) => {
  if (!result) return
  
  const historyItem = {
    title: result.title,
    url: form.url,
    platform: result.platform,
    parseTime: new Date().toLocaleString(),
    result: result
  }
  
  // 这里可以调用API保存到后端，或者保存到localStorage
  // 示例使用localStorage
  const history = JSON.parse(localStorage.getItem('parseHistory') || '[]')
  // 检查是否已存在相同URL的记录
  const existingIndex = history.findIndex(item => item.url === form.url)
  if (existingIndex !== -1) {
    // 更新已存在的记录
    history[existingIndex] = historyItem
  } else {
    // 添加新记录，限制最多保存20条
    history.unshift(historyItem)
    if (history.length > 20) {
      history.pop()
    }
  }
  localStorage.setItem('parseHistory', JSON.stringify(history))
}

// 获取历史记录
const getHistory = () => {
  // 这里可以调用API从后端获取，或者从localStorage获取
  // 示例使用localStorage
  const history = JSON.parse(localStorage.getItem('parseHistory') || '[]')
  parseHistory.value = history
}

// 加载历史记录项
const loadHistoryItem = (item) => {
  form.url = item.url
  parseResult.value = item.result
}

// 删除历史记录项
const removeHistoryItem = (index) => {
  ElMessageBox.confirm('确定要删除这条历史记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const history = JSON.parse(localStorage.getItem('parseHistory') || '[]')
    history.splice(index, 1)
    localStorage.setItem('parseHistory', JSON.stringify(history))
    parseHistory.value = history
    ElMessage.success('删除成功')
  }).catch(() => {})
}

onMounted(() => {
  getHistory()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-container {
  margin-bottom: 20px;
}

.result-container {
  margin-top: 20px;
}

.video-info {
  .video-title {
    margin-bottom: 10px;
    h3 {
      margin: 0;
    }
  }
  
  .video-meta {
    display: flex;
    gap: 15px;
    color: #606266;
    font-size: 14px;
    margin-bottom: 15px;
  }
  
  .video-cover {
    margin-bottom: 15px;
    
    .el-image {
      max-width: 100%;
      max-height: 300px;
      border-radius: 4px;
    }
  }
  
  .video-player {
    margin-bottom: 20px;
  }
  
  .download-options {
    margin-top: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
}

.history-container {
  margin-top: 30px;
}

.tips-container {
  margin-top: 30px;
}
</style>